<template>
  <div class="master-detail-container" v-loading="loading" element-loading-text="正在加载短剧列表...">
    <!-- Master Pane -->
    <div class="master-pane">
      <div class="master-header">
        <div class="search-container">
          <el-input
            v-model="searchQuery"
            placeholder="搜索名称、简介、分类"
            clearable
            :prefix-icon="SearchIcon"
            @clear="clearSearch"
            @keyup.enter="performQuickSearch(searchQuery)"
          />
          
          <!-- 搜索建议下拉框 -->
          <div v-if="isSearchMode && searchResults.length > 0" class="search-suggestions">
            <div class="suggestions-header">
              <span>相关分类</span>
            </div>
            <div class="suggestions-list">
              <el-tag
                v-for="category in getTopCategories()"
                :key="category"
                size="small"
                type="info"
                effect="light"
                @click="searchQuery = category"
                style="margin: 2px; cursor: pointer;"
              >
                {{ category }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
      <div class="drama-list-container">
        <el-scrollbar>
          <div v-if="displayedDramas.length > 0" class="drama-list">
            <div
              v-for="drama in displayedDramas"
              :key="drama.id"
              class="drama-list-item"
              :class="{ 'active': selectedDrama && selectedDrama.id === drama.id }"
              @click="selectDrama(drama)"
            >
              <el-image
                :src="drama.coverImageUrl"
                class="item-cover"
                fit="cover"
                lazy
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="item-info">
                <div class="item-title-row">
                  <span class="item-title" :title="drama.title">{{ drama.title }}</span>
                  <span class="item-score">
                    <el-icon><StarFilled /></el-icon>
                    {{ drama.score || 'N/A' }}
                  </span>
                </div>
                <div class="item-meta">
                  <span><el-icon><Collection /></el-icon> {{ drama.episodeCount }}集</span>
                  <!-- 字幕状态显示 -->
                  <span class="item-subtitle-status" v-if="getSubtitleStatus(drama.id)">
                    <el-tooltip 
                      :content="getSubtitleStatus(drama.id)?.message || ''"
                      placement="top"
                      effect="dark"
                    >
                      <el-tag 
                        :type="getStatusDisplay(getSubtitleStatus(drama.id)).type"
                        size="small"
                        effect="light"
                        class="status-tag"
                      >
                        <el-icon v-if="getStatusDisplay(getSubtitleStatus(drama.id)).type === 'success'">
                          <Check />
                        </el-icon>
                        <el-icon v-else>
                          <Select />
                        </el-icon>
                        {{ getStatusDisplay(getSubtitleStatus(drama.id)).text }}
                      </el-tag>
                    </el-tooltip>
                  </span>
                  <!-- 状态加载中显示 -->
                  <span class="item-subtitle-status" v-else-if="statusLoading">
                    <el-tag type="info" size="small" effect="light" class="status-tag">
                      <el-icon class="is-loading"><Loading /></el-icon>
                      加载中
                    </el-tag>
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div v-else-if="loading" class="drama-list-loading">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>正在加载短剧列表...</span>
          </div>
          <el-empty
            v-else
            :description="getEmptyDescription()"
            class="master-empty"
            :image-size="100"
          >
            <template #image>
              <el-icon size="80" color="var(--text-color-placeholder)">
                <component :is="getEmptyIcon()" />
              </el-icon>
            </template>
          </el-empty>
        </el-scrollbar>
      </div>

      <!-- 分页控件 -->
      <div class="master-pagination" v-if="!isSearchMode && paginationStats.totalPages > 1">
        <el-pagination
          :current-page="paginationStats.currentPage"
          :page-size="20"
          :total="paginationStats.total"
          layout="total, prev, pager, next, jumper"
          @current-change="handlePageChange"
          small
          background
          :pager-count="5"
          :disabled="paginationStats.loading"
        />
      </div>

      <!-- 分页信息提示 -->
      <div class="pagination-info" v-if="!isSearchMode && paginationStats.total > 0">
        <span class="pagination-text">
          显示第 {{ (paginationStats.currentPage - 1) * 20 + 1 }} -
          {{ Math.min(paginationStats.currentPage * 20, paginationStats.total) }} 条，
          共 {{ paginationStats.total }} 条记录
        </span>
      </div>

      <!-- 搜索信息提示 -->
      <div class="search-info" v-if="isSearchMode">
        <span class="search-text">
          <template v-if="searchLoading">
            <el-icon class="is-loading"><Loading /></el-icon>
            正在搜索"{{ searchKeyword }}"...
          </template>
          <template v-else>
            搜索"{{ searchKeyword }}"找到 {{ searchTotal }} 条结果
            <span v-if="lastSearchTime > 0" class="search-time">
              ({{ lastSearchTime }}ms)
            </span>
            <el-button 
              link 
              type="primary" 
              size="small" 
              @click="clearSearch"
              style="margin-left: 8px;"
            >
              清除搜索
            </el-button>
          </template>
        </span>
      </div>
    </div>

    <!-- Detail Pane -->
    <div class="detail-pane">
      <div v-if="selectedDrama" class="detail-content-wrapper" v-loading="detailLoading" element-loading-text="正在加载剧集信息...">
        <el-scrollbar>
          <div class="detail-header">
            <h2 class="detail-title" :title="selectedDrama.title">{{ selectedDrama.title }}</h2>
            <div class="detail-score">
              <el-icon><StarFilled /></el-icon>
              <strong>{{ selectedDrama.score || 'N/A' }}</strong>
            </div>
          </div>
          <div class="detail-body">
            <div class="detail-cover-wrapper">
              <el-image :src="selectedDrama.coverImageUrl" class="detail-cover" fit="cover">
                 <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="detail-info-section">
              <h3>基本信息</h3>
              <div class="info-grid">
                <div class="info-item"><el-icon><Notebook /></el-icon><span>总集数</span><strong>{{ selectedDrama.episodeCount }}</strong></div>
                <div class="info-item"><el-icon><Pointer /></el-icon><span>点击数</span><strong>{{ selectedDrama.clickCount || 0 }}</strong></div>
                <div class="info-item"><el-icon><Star /></el-icon><span>点赞数</span><strong>{{ selectedDrama.likeCount || 0 }}</strong></div>
                <div class="info-item"><el-icon><User /></el-icon><span>创建者</span><strong>{{ selectedDrama.createBy }}</strong></div>
                <!-- 字幕状态显示 -->
                <div class="info-item full-width" v-if="getSubtitleStatus(selectedDrama.id)">
                  <el-icon><Select /></el-icon>
                  <span>字幕状态</span>
                  <strong>
                    <el-tag 
                      :type="getStatusDisplay(getSubtitleStatus(selectedDrama.id)).type"
                      size="small"
                      effect="light"
                    >
                      <el-icon v-if="getStatusDisplay(getSubtitleStatus(selectedDrama.id)).type === 'success'">
                        <Check />
                      </el-icon>
                      {{ getStatusDisplay(getSubtitleStatus(selectedDrama.id)).text }}
                    </el-tag>
                    <span class="status-detail" v-if="getSubtitleStatus(selectedDrama.id)">
                      ({{ getSubtitleStatus(selectedDrama.id)?.message }})
                    </span>
                    <el-button 
                      link 
                      type="primary" 
                      size="small" 
                      @click="refreshSingleStatus(selectedDrama.id)"
                      style="margin-left: 8px;"
                    >
                      <el-icon><Refresh /></el-icon>
                      刷新
                    </el-button>
                  </strong>
                </div>
                <div class="info-item full-width"><el-icon><Timer /></el-icon><span>创建时间</span><strong>{{ selectedDrama.createTime }}</strong></div>
                <div class="info-item full-width"><el-icon><EditPen /></el-icon><span>更新时间</span><strong>{{ selectedDrama.updateTime }}</strong></div>
              </div>
              <div class="detail-categories">
                 <h3>分类标签</h3>
                 <el-space wrap size="small">
                    <el-tag v-for="cat in selectedDrama.categoryName" :key="cat" type="primary" effect="light" size="small">{{ cat.trim() }}</el-tag>
                    <span v-if="!selectedDrama.categoryName || selectedDrama.categoryName.length === 0" class="text-secondary">暂无分类</span>
                 </el-space>
              </div>
            </div>
          </div>
          <div class="detail-description-section">
            <h3>简介</h3>
            <p class="description-text">{{ selectedDrama.description || '暂无简介' }}</p>
          </div>
          
          <!-- Tabs for Episodes and Subtitles -->
          <div class="detail-tabs-section">
            <el-tabs v-model="activeTab" type="border-card" class="detail-tabs">
              <el-tab-pane label="剧集列表" name="episodes">
                <el-table :data="paginatedEpisodes" stripe style="width: 100%" empty-text="暂无剧集数据" size="small">
                  <el-table-column prop="episodeId" label="ID" width="80" align="center" />
                  <el-table-column prop="videoUrl" label="视频URL" :show-overflow-tooltip="true" min-width="180" />
                  <el-table-column prop="vip" label="VIP" width="80" align="center">
                    <template #default="{ row }">
                      <el-tag :type="row.vip ? 'warning' : 'success'" effect="dark" size="small">{{ row.vip ? '是' : '否' }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="状态" width="80" align="center">
                    <template #default="{ row }">
                      <el-tag :type="row.status === 0 ? 'success' : 'danger'" size="small">{{ row.status === 0 ? '启用' : '禁用' }}</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="episode-pagination" style="margin-top: 15px; display: flex; justify-content: flex-end;">
                  <el-pagination 
                    :current-page="episodeCurrentPage" 
                    :page-size="episodePageSize" 
                    :page-sizes="[10, 20, 50, 100]" 
                    layout="total, sizes, prev, pager, next" 
                    :total="episodes.length" 
                    @size-change="handleEpisodeSizeChange" 
                    @current-change="handleEpisodeCurrentChange" 
                    small 
                  />
                </div>
              </el-tab-pane>
              <el-tab-pane label="字幕状态" name="subtitles">
                <!-- 字幕加载状态 -->
                <div v-if="subtitleLoading" class="subtitle-loading">
                  <el-icon class="is-loading"><Loading /></el-icon>
                  <span>正在加载字幕数据...</span>
                </div>

                <!-- 字幕内容 -->
                <template v-else-if="subtitleLoaded">
                  <!-- 字幕刷新状态 -->
                  <div v-if="subtitleRefreshing" class="subtitle-refreshing">
                    <el-icon class="is-loading"><Loading /></el-icon>
                    <span>正在刷新字幕数据...</span>
                  </div>

                  <div class="subtitle-controls">
                    <div class="filter-section">
                      <div class="filter-label">国家:</div>
                      <el-checkbox-group v-model="subtitleCountryFilter" size="small">
                        <el-checkbox-button :label="0">全部</el-checkbox-button>
                        <el-checkbox-button v-for="c in subtitleCountries" :key="c.countryId" :label="c.countryId">{{ c.countryName }}</el-checkbox-button>
                      </el-checkbox-group>
                    </div>
                    <div class="filter-section">
                      <div class="filter-label">状态:</div>
                      <el-radio-group v-model="subtitleStatusFilter" size="small">
                        <el-radio-button label="all">全部</el-radio-button>
                        <el-radio-button label="ready">有字幕</el-radio-button>
                        <el-radio-button label="missing">无字幕</el-radio-button>
                      </el-radio-group>
                    </div>
                    <div class="filter-section">
                      <el-button
                        type="primary"
                        size="small"
                        :loading="subtitleRefreshing"
                        :disabled="subtitleRefreshing"
                        @click="refreshSubtitleData"
                        class="refresh-button"
                      >
                        <template #icon>
                          <el-icon><Refresh /></el-icon>
                        </template>
                        {{ subtitleRefreshing ? '刷新中...' : '刷新字幕' }}
                      </el-button>
                    </div>
                    <!-- 批量选择区域 -->
                    <div class="filter-section selection-section">
                      <div class="filter-label">批量选择:</div>
                      <el-button-group size="small">
                        <el-button
                          :type="isAllSelected ? 'primary' : 'default'"
                          :icon="isAllSelected ? 'Select' : isPartialSelected ? 'SemiSelect' : 'Select'"
                          @click="toggleSelectAll"
                          :disabled="allSelectableEpisodeIds.length === 0"
                        >
                          {{ isAllSelected ? '全不选' : '全选' }}
                        </el-button>
                        <el-button
                          type="info"
                          @click="clearSelection"
                          :disabled="selectedCount === 0"
                        >
                          清空 ({{ selectedCount }})
                        </el-button>
                      </el-button-group>
                    </div>
                    
                    <!-- 选中剧集ID显示区域 -->
                    <div class="filter-section selected-episodes-section" v-if="selectedCount > 0">
                      <div class="filter-label">已选剧集ID:</div>
                      <div class="selected-episodes-display">
                        <div class="episodes-tags-container">
                          <el-tag
                            v-for="episodeId in sortedSelectedEpisodeIds.slice(0, 10)"
                            :key="episodeId"
                            size="small"
                            type="warning"
                            effect="light"
                            closable
                            @close="toggleEpisodeSelection(episodeId)"
                            class="episode-id-tag"
                          >
                            {{ episodeId }}
                          </el-tag>
                          <el-tag
                            v-if="selectedCount > 10"
                            size="small"
                            type="info"
                            effect="light"
                            class="more-episodes-tag"
                          >
                            ...还有{{ selectedCount - 10 }}个
                          </el-tag>
                        </div>
                        <div class="episodes-summary">
                          <span class="summary-text">
                            共{{ selectedCount }}集：{{ selectedEpisodesRange }}
                          </span>
                        </div>
                      </div>
                    </div>
                    
                    <!-- 删除操作区域 -->
                    <div class="filter-section delete-section">
                      <div class="filter-label">删除操作:</div>
                      <el-button-group size="small">
                        <el-button
                          type="warning"
                          :loading="deletingBatch"
                          :disabled="deletingBatch || deletingDrama || subtitleRefreshing || selectedCount === 0"
                          @click="deleteBatchSelectedSubtitles"
                          class="delete-button"
                        >
                          <template #icon>
                            <el-icon><Delete /></el-icon>
                          </template>
                          {{ deletingBatch ? '删除中...' : `删除选中(${selectedCount})` }}
                        </el-button>
                        <el-button
                          type="danger"
                          :loading="deletingDrama"
                          :disabled="deletingDrama || deletingBatch || subtitleRefreshing || filteredSubtitleEpisodes.length === 0"
                          @click="confirmDeleteAllSubtitles"
                          class="delete-button"
                        >
                          <template #icon>
                            <el-icon><Delete /></el-icon>
                          </template>
                          {{ deletingDrama ? '删除中...' : '删除全部字幕' }}
                        </el-button>
                      </el-button-group>
                    </div>
                  </div>
                  <div class="subtitle-table-container">
                    <el-table :data="paginatedSubtitleEpisodes" size="small" border>
                      <!-- 选择列 -->
                      <el-table-column type="selection" width="50" align="center" fixed="left" :selectable="(row: Episode) => hasEpisodeSubtitles(row.episodeId)">
                        <template #header>
                          <el-checkbox
                            v-model="isAllSelected"
                            :indeterminate="isPartialSelected"
                            @change="toggleSelectAll"
                            :disabled="allSelectableEpisodeIds.length === 0"
                          />
                        </template>
                        <template #default="scope">
                          <el-checkbox
                            :model-value="isEpisodeSelected(scope.row.episodeId)"
                            @change="toggleEpisodeSelection(scope.row.episodeId)"
                            :disabled="!hasEpisodeSubtitles(scope.row.episodeId)"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column prop="episodeId" label="ID" width="70" align="center" fixed="left" />
                      <template v-for="country in filteredCountries" :key="country.countryId">
                        <el-table-column :label="country.countryName" min-width="40" align="center" class-name="lang-column">
                          <template #header><div class="vertical-header">{{ country.countryName }}</div></template>
                          <template #default="scope">
                            <el-tooltip
                              :disabled="!getSubtitleByCountry(scope.row.episodeId, country.countryId)"
                              :content="getSubtitleByCountry(scope.row.episodeId, country.countryId)?.subtitleFile?.split('/').pop() ?? ''"
                              placement="top"
                              effect="dark"
                             >
                              <div
                                class="status-cell"
                                :class="{ 'has-subtitle': getSubtitleByCountry(scope.row.episodeId, country.countryId) }"
                              >
                                <!-- 移除对号图标，仅使用色块填充 -->
                              </div>
                            </el-tooltip>
                          </template>
                        </el-table-column>
                      </template>
                      <!-- 操作列 -->
                      <el-table-column label="操作" width="80" align="center" fixed="right">
                        <template #default="scope">
                          <el-button
                            type="danger"
                            size="small"
                            :loading="deletingEpisode === scope.row.episodeId"
                            :disabled="deletingEpisode !== null || deletingDrama || deletingBatch || !hasEpisodeSubtitles(scope.row.episodeId)"
                            @click="deleteEpisodeSubtitle(scope.row.episodeId)"
                            title="删除此集字幕"
                          >
                            <template #icon>
                              <el-icon><Delete /></el-icon>
                            </template>
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                  <div class="subtitle-pagination">
                    <el-pagination :current-page="subtitleCurrentPage" :page-size="subtitlePageSize" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" :total="filteredSubtitleEpisodes.length" @size-change="handleSubtitleSizeChange" @current-change="handleSubtitleCurrentChange" small />
                  </div>
                </template>

                <!-- 未加载状态提示 -->
                <div v-else class="subtitle-placeholder">
                  <el-empty description="点击此标签页加载字幕数据" :image-size="80">
                    <template #image>
                      <el-icon size="60" color="var(--text-color-placeholder)">
                        <Notebook />
                      </el-icon>
                    </template>
                  </el-empty>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-scrollbar>
      </div>
      <div v-else class="detail-placeholder">
        <el-empty description="请从左侧选择一个短剧查看详情" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Picture, Search as SearchIcon, Star, StarFilled,
  Collection, Notebook, Pointer, User, Timer, EditPen,
  Loading, FolderOpened, DocumentRemove, Refresh, Select, Check, Delete
} from '@element-plus/icons-vue';
import {
  getDramasPaginated, getDramaEpisodes, getCountrySelectList, getSubtitlesByShortDramaId,
  quickSearch, debouncedSearch, cancelDebouncedSearch,
  getSubtitleCompletionStatus, getBatchSubtitleCompletionStatus,
  deleteEpisodeSubtitles, deleteDramaSubtitles, deleteBatchEpisodeSubtitles,
  type Drama, type Episode, type LanguageOption, type Subtitle, type SearchResult, type SubtitleCompletionStatus,
} from '../api/drama';
import { PaginationManager } from '../utils/paginationManager';

// --- Core State ---
const dramas = ref<Drama[]>([]);
const loading = ref(false);
const detailLoading = ref(false);
const searchQuery = ref('');
const selectedDrama = ref<Drama | null>(null);
const activeTab = ref('episodes');

// --- Search State ---
const isSearchMode = ref(false);
const searchResults = ref<Drama[]>([]);
const searchLoading = ref(false);
const searchTotal = ref(0);
const searchKeyword = ref('');
const lastSearchTime = ref(0);

// --- Pagination State ---
const paginationManager = ref<PaginationManager<Drama> | null>(null);
const paginationStats = ref({
  currentPage: 1,
  totalPages: 0,
  total: 0,
  hasMore: false,
  loading: false
});

// --- Episodes & Subtitles State ---
const episodes = ref<Episode[]>([]);
const episodeCurrentPage = ref(1);
const episodePageSize = ref(10);
const subtitles = ref<Subtitle[]>([]);
const subtitleCountries = ref<LanguageOption[]>([]);
const subtitleCountryFilter = ref<number[]>([0]); // 0 for All
const subtitleStatusFilter = ref('all');
const subtitleCurrentPage = ref(1);
const subtitlePageSize = ref(10);

// --- Subtitle Loading State ---
const subtitleLoading = ref(false);
const subtitleLoaded = ref(false); // 标记当前短剧的字幕是否已加载
const subtitleRefreshing = ref(false); // 标记是否正在刷新字幕数据

// --- Subtitle Status State ---
const subtitleStatusMap = ref<Map<number, SubtitleCompletionStatus>>(new Map()); // 字幕完成状态映射
const statusLoading = ref(false); // 状态加载中标志
const statusLoadingProgress = ref({ completed: 0, total: 0 }); // 状态加载进度

// --- Subtitle Delete State ---
const deletingDrama = ref(false); // 正在删除整部剧字幕
const deletingEpisode = ref<number | null>(null); // 正在删除的剧集ID
const deletingBatch = ref(false); // 正在批量删除选中剧集字幕
const selectedEpisodeIds = ref<Set<number>>(new Set()); // 选中的剧集ID集合

// --- Computed: Master List ---
const displayedDramas = computed(() => {
  if (isSearchMode.value) {
    // 搜索模式：显示搜索结果
    return searchResults.value;
  } else {
    // 分页模式：显示当前页数据
    return paginationManager.value?.getCurrentPageData() || dramas.value;
  }
});

// 兼容性计算属性（保留原有的filteredDramas以避免破坏其他代码）
const filteredDramas = computed(() => displayedDramas.value);

// --- Computed: Episode Tab ---
const sortedEpisodes = computed(() => {
  return [...episodes.value].sort((a, b) => a.episodeId - b.episodeId);
});

const paginatedEpisodes = computed(() => {
  const startIndex = (episodeCurrentPage.value - 1) * episodePageSize.value;
  return sortedEpisodes.value.slice(startIndex, startIndex + episodePageSize.value);
});

// --- Computed: Subtitle Tab ---
const filteredCountries = computed(() => {
  if (subtitleCountryFilter.value.includes(0) || subtitleCountryFilter.value.length === 0) {
    return subtitleCountries.value;
  }
  return subtitleCountries.value.filter(c => subtitleCountryFilter.value.includes(c.countryId));
});

const filteredSubtitleEpisodes = computed(() => {
  let filtered = sortedEpisodes.value;
  if (subtitleStatusFilter.value !== 'all') {
    filtered = filtered.filter(ep => {
      const hasAnySubtitle = filteredCountries.value.some(country => getSubtitleByCountry(ep.episodeId, country.countryId));
      return subtitleStatusFilter.value === 'ready' ? hasAnySubtitle : !hasAnySubtitle;
    });
  }
  return filtered;
});

const paginatedSubtitleEpisodes = computed(() => {
  const startIndex = (subtitleCurrentPage.value - 1) * subtitlePageSize.value;
  return filteredSubtitleEpisodes.value.slice(startIndex, startIndex + subtitlePageSize.value);
});

const getSubtitleByCountry = (episodeId: number, countryId: number) => {
  return subtitles.value.find(s => s.episodeId === episodeId && s.countryId === countryId);
};

// 检查某个剧集是否有字幕
const hasEpisodeSubtitles = (episodeId: number) => {
  return subtitles.value.some(s => s.episodeId === episodeId);
};

// --- Computed: Subtitle Selection ---
const allSelectableEpisodeIds = computed(() => {
  // 只能选择有字幕的剧集
  return filteredSubtitleEpisodes.value
    .filter(ep => hasEpisodeSubtitles(ep.episodeId))
    .map(ep => ep.episodeId);
});

const isAllSelected = computed(() => {
  const selectableIds = allSelectableEpisodeIds.value;
  return selectableIds.length > 0 && selectableIds.every(id => selectedEpisodeIds.value.has(id));
});

const isPartialSelected = computed(() => {
  const selectableIds = allSelectableEpisodeIds.value;
  const selectedCount = selectableIds.filter(id => selectedEpisodeIds.value.has(id)).length;
  return selectedCount > 0 && selectedCount < selectableIds.length;
});

const selectedCount = computed(() => {
  return selectedEpisodeIds.value.size;
});

// 排序后的选中剧集ID列表
const sortedSelectedEpisodeIds = computed(() => {
  return Array.from(selectedEpisodeIds.value).sort((a, b) => a - b);
});

// 选中剧集的范围显示
const selectedEpisodesRange = computed(() => {
  if (selectedEpisodeIds.value.size === 0) return '';
  
  const sortedIds = sortedSelectedEpisodeIds.value;
  if (sortedIds.length === 1) return sortedIds[0].toString();
  
  // 生成范围显示，如 "1-5, 8-12, 15"
  const ranges: string[] = [];
  let rangeStart = sortedIds[0];
  let rangeEnd = sortedIds[0];
  
  for (let i = 1; i < sortedIds.length; i++) {
    if (sortedIds[i] === rangeEnd + 1) {
      // 连续的数字，扩展范围
      rangeEnd = sortedIds[i];
    } else {
      // 不连续，添加当前范围到结果
      if (rangeStart === rangeEnd) {
        ranges.push(rangeStart.toString());
      } else {
        ranges.push(`${rangeStart}-${rangeEnd}`);
      }
      rangeStart = rangeEnd = sortedIds[i];
    }
  }
  
  // 添加最后一个范围
  if (rangeStart === rangeEnd) {
    ranges.push(rangeStart.toString());
  } else {
    ranges.push(`${rangeStart}-${rangeEnd}`);
  }
  
  return ranges.join(', ');
});

// --- Computed: Subtitle Status ---
const getSubtitleStatus = (dramaId: number): SubtitleCompletionStatus | null => {
  return subtitleStatusMap.value.get(dramaId) || null;
};

const getStatusDisplay = (status: SubtitleCompletionStatus | null) => {
  if (!status) {
    return { text: '未知', type: 'info', percentage: 0 };
  }
  
  const percentage = status.totalEpisodes > 0 ? Math.round((status.uploadedSubtitles / status.totalEpisodes) * 100) : 0;
  
  if (status.subtitleStatus === 0) {
    return { text: '已完成', type: 'success', percentage: 100 };
  } else {
    return { 
      text: `${status.uploadedSubtitles}/${status.totalEpisodes}`, 
      type: percentage > 50 ? 'warning' : 'danger', 
      percentage 
    };
  }
};

// --- Watchers ---
watch(filteredDramas, (newDramas) => {
  if (selectedDrama.value && !newDramas.some(d => d.id === selectedDrama.value!.id)) {
    selectedDrama.value = null;
  }
});

// 监听标签页切换，当切换到字幕标签页时加载字幕数据
watch(activeTab, (newTab) => {
  if (newTab === 'subtitles' && selectedDrama.value && !subtitleLoaded.value) {
    loadSubtitleData();
  }
  // 切换标签页时清空选择
  clearSelection();
});

// 搜索时的处理
watch(searchQuery, (newQuery) => {
  handleSearchInput(newQuery);
});

// 监听显示的短剧变化，自动加载字幕状态
watch(displayedDramas, (newDramas) => {
  if (newDramas.length > 0) {
    // 延迟加载状态，避免频繁请求
    setTimeout(() => {
      loadSubtitleStatuses();
    }, 100);
  }
});

// 组件销毁时清理搜索
watch(() => {}, () => {}, {
  // 这里可以添加额外的 cleanup 逻辑
});

watch(subtitleCountryFilter, (newVal, oldVal) => {
  if (newVal.length === 0) {
    // Prevent unselecting everything, default to 'All'
    subtitleCountryFilter.value = [0];
    return;
  }
  
  // If 'All' was selected and a country is added
  if (oldVal.includes(0) && newVal.length > 1) {
    subtitleCountryFilter.value = newVal.filter(id => id !== 0);
    return;
  }

  // If a country/countries were selected and 'All' is added
  if (!oldVal.includes(0) && newVal.includes(0)) {
    subtitleCountryFilter.value = [0];
    return;
  }
});

// --- Methods ---
const initializePagination = () => {
  paginationManager.value = new PaginationManager<Drama>(
    async (pageNum: number, pageSize: number) => {
      return await getDramasPaginated(pageNum, pageSize);
    },
    {
      pageSize: 20,
      preloadPages: 0,
      cachePages: 0
    }
  );
};

// --- Search Methods ---
/**
 * 处理搜索输入
 */
const handleSearchInput = (keyword: string) => {
  searchKeyword.value = keyword.trim();
  
  if (!searchKeyword.value) {
    // 清空搜索，回到分页模式
    clearSearch();
    return;
  }

  // 进入搜索模式
  isSearchMode.value = true;
  searchLoading.value = true;

  // 使用防抖搜索
  debouncedSearch(
    searchKeyword.value,
    (results: SearchResult<Drama[]>) => {
      searchResults.value = results.rows || [];
      searchTotal.value = results.total || 0;
      lastSearchTime.value = results.searchTime || 0;
      searchLoading.value = false;
      
      console.log(`🔍 搜索完成: 关键词="${searchKeyword.value}", 结果数=${searchResults.value.length}, 耗时=${lastSearchTime.value}ms`);
    },
    {
      delay: 300,
      pageSize: 50 // 搜索时显示更多结果
    }
  );
};

/**
 * 清除搜索状态
 */
const clearSearch = () => {
  isSearchMode.value = false;
  searchResults.value = [];
  searchTotal.value = 0;
  searchKeyword.value = '';
  searchLoading.value = false;
  lastSearchTime.value = 0;
  
  // 取消pending的搜索请求
  if (searchQuery.value) {
    cancelDebouncedSearch(searchQuery.value);
  }
};

/**
 * 执行快速搜索（用于手动搜索）
 */
const performQuickSearch = async (keyword: string, page: number = 1) => {
  if (!keyword.trim()) return;

  searchLoading.value = true;
  try {
    const results = await quickSearch(keyword.trim(), page, 50);
    searchResults.value = results.rows || [];
    searchTotal.value = results.total || 0;
    lastSearchTime.value = results.searchTime || 0;
    
    console.log(`⚡ 快速搜索完成: 关键词="${keyword}", 结果数=${searchResults.value.length}, 耗时=${lastSearchTime.value}ms`);
  } catch (error) {
    console.error('搜索失败:', error);
    searchResults.value = [];
    searchTotal.value = 0;
  } finally {
    searchLoading.value = false;
  }
};

const fetchDramas = async () => {
  loading.value = true;
  try {
    if (!paginationManager.value) {
      initializePagination();
    }

    const data = await paginationManager.value!.goToPage(1);
    dramas.value = data.sort((a,b) => a.id - b.id);

    // 更新分页统计
    updatePaginationStats();
  } catch (err) {
    console.error('获取剧集列表失败', err);
    dramas.value = [];
  } finally {
    loading.value = false;
  }
};

const updatePaginationStats = () => {
  if (paginationManager.value) {
    const stats = paginationManager.value.getStats();
    paginationStats.value = {
      currentPage: stats.currentPage,
      totalPages: stats.totalPages,
      total: stats.total,
      hasMore: stats.hasMore,
      loading: stats.loading
    };
  }
};

const handlePageChange = async (page: number) => {
  if (!paginationManager.value) return;

  loading.value = true;
  try {
    const data = await paginationManager.value.goToPage(page);
    dramas.value = data.sort((a,b) => a.id - b.id);
    updatePaginationStats();
  } catch (err) {
    console.error('切换页面失败', err);
  } finally {
    loading.value = false;
  }
};

const selectDrama = async (drama: Drama) => {
  if (selectedDrama.value?.id === drama.id) return;

  selectedDrama.value = drama;
  detailLoading.value = true;
  activeTab.value = 'episodes';
  subtitleCurrentPage.value = 1;
  episodeCurrentPage.value = 1;

  // 重置字幕加载状态
  subtitleLoaded.value = false;
  subtitles.value = [];
  
  // 清空选择
  clearSelection();

  try {
    // 只加载剧集数据，字幕数据延迟到点击字幕标签页时加载
    const episodesRes = await getDramaEpisodes(drama.id);
    episodes.value = episodesRes;

  } catch (err) {
    console.error('获取剧集数据失败', err);
    episodes.value = [];
  } finally {
    detailLoading.value = false;
  }
};

const handleEpisodeSizeChange = (val: number) => { episodePageSize.value = val; };
const handleEpisodeCurrentChange = (val: number) => { episodeCurrentPage.value = val; };
const handleSubtitleSizeChange = (val: number) => { subtitlePageSize.value = val; };
const handleSubtitleCurrentChange = (val: number) => { subtitleCurrentPage.value = val; };

// 延迟加载字幕数据 (使用新版API - 直接通过shortDramaId查询)
const loadSubtitleData = async (forceRefresh: boolean = false) => {
  if (!selectedDrama.value || (subtitleLoaded.value && !forceRefresh)) return;

  const isRefreshing = forceRefresh && subtitleLoaded.value;
  if (isRefreshing) {
    subtitleRefreshing.value = true;
  } else {
    subtitleLoading.value = true;
  }

  try {
    const actionText = forceRefresh ? '刷新' : '加载';
    console.log(`🚀 开始${actionText}字幕: 短剧="${selectedDrama.value.title}", 短剧ID=${selectedDrama.value.id}`);

    // 先获取国家列表
    if (!forceRefresh || !subtitleCountries.value.length) {
      subtitleCountries.value = await getCountrySelectList();
    }

    // 如果是刷新，先清空当前数据
    if (forceRefresh) {
      subtitles.value = [];
    }

    // 使用新版API直接通过shortDramaId获取字幕数据
    const subtitlesRes = await getSubtitlesByShortDramaId(selectedDrama.value.id, (currentSubtitles, completedPages, totalPages) => {
      // 实时更新字幕数据
      subtitles.value = [...currentSubtitles];

      const progress = Math.round((completedPages / totalPages) * 100);
      console.log(`📊 字幕${actionText}进度: 第${completedPages}/${totalPages}页 (${progress}%) - 当前字幕数量: ${currentSubtitles.length}`);
    }, forceRefresh);

    // 最终设置完整数据
    subtitles.value = subtitlesRes;
    subtitleLoaded.value = true;

    console.log(`✅ 字幕${actionText}完成: 短剧="${selectedDrama.value.title}", 短剧ID=${selectedDrama.value.id}, 字幕数量=${subtitlesRes.length}`);
  } catch (err) {
    console.error(`获取字幕数据失败`, err);
    if (!forceRefresh) {
      subtitles.value = [];
      subtitleCountries.value = [];
    }
  } finally {
    subtitleLoading.value = false;
    subtitleRefreshing.value = false;
  }
};

// 刷新字幕数据
const refreshSubtitleData = async () => {
  if (!selectedDrama.value || subtitleRefreshing.value) return;

  console.log(`🔄 手动刷新字幕数据: 短剧="${selectedDrama.value.title}"`);
  await loadSubtitleData(true);
};

// 空状态处理
const getEmptyDescription = () => {
  if (isSearchMode.value) {
    if (searchLoading.value) {
      return `正在搜索"${searchKeyword.value}"...`;
    }
    return `未找到包含"${searchKeyword.value}"的短剧`;
  }
  return '暂无短剧数据';
};

const getEmptyIcon = () => {
  if (isSearchMode.value) {
    return DocumentRemove;
  }
  return FolderOpened;
};

// 获取搜索建议的分类
const getTopCategories = () => {
  const categoryMap: { [key: string]: number } = {};
  searchResults.value.forEach(drama => {
    drama.categoryName.forEach(cat => {
      categoryMap[cat] = (categoryMap[cat] || 0) + 1;
    });
  });
  return Object.entries(categoryMap)
    .sort(([, countA], [, countB]) => countB - countA)
    .map(([category]) => category)
    .slice(0, 5); // 显示前5个最热门的分类
};

// --- Subtitle Status Methods ---
/**
 * 加载当前显示短剧的字幕状态
 */
const loadSubtitleStatuses = async () => {
  const currentDramas = displayedDramas.value;
  if (!currentDramas.length) return;

  const dramaIds = currentDramas.map(d => d.id);
  statusLoading.value = true;
  statusLoadingProgress.value = { completed: 0, total: dramaIds.length };

  try {
    console.log(`🔄 开始加载字幕状态: ${dramaIds.length}个短剧`);
    
    const statuses = await getBatchSubtitleCompletionStatus(
      dramaIds,
      (statusMap, completed, total) => {
        // 实时更新状态映射
        subtitleStatusMap.value = new Map(statusMap);
        statusLoadingProgress.value = { completed, total };
        
        console.log(`📊 字幕状态加载进度: ${completed}/${total}`);
      }
    );

    // 最终更新状态映射
    subtitleStatusMap.value = statuses;
    
    const completedCount = Array.from(statuses.values()).filter(s => s.subtitleStatus === 0).length;
    console.log(`✅ 字幕状态加载完成: ${statuses.size}个短剧, ${completedCount}个已完成`);
  } catch (error) {
    console.error('加载字幕状态失败:', error);
  } finally {
    statusLoading.value = false;
  }
};

/**
 * 刷新单个短剧的字幕状态
 */
const refreshSingleStatus = async (dramaId: number) => {
  try {
    const status = await getSubtitleCompletionStatus(dramaId);
    subtitleStatusMap.value.set(dramaId, status);
    console.log(`🔄 刷新状态完成: 短剧${dramaId}, 状态=${status.subtitleStatus === 0 ? '完成' : '未完成'}`);
  } catch (error) {
    console.error(`刷新短剧${dramaId}状态失败:`, error);
  }
};

// --- Subtitle Selection Methods ---

/**
 * 切换剧集选择状态
 */
const toggleEpisodeSelection = (episodeId: number) => {
  if (selectedEpisodeIds.value.has(episodeId)) {
    selectedEpisodeIds.value.delete(episodeId);
  } else {
    selectedEpisodeIds.value.add(episodeId);
  }
};

/**
 * 全选/反选所有可选择的剧集
 */
const toggleSelectAll = () => {
  const selectableIds = allSelectableEpisodeIds.value;
  if (isAllSelected.value) {
    // 如果已全选，则清空选择
    selectedEpisodeIds.value.clear();
  } else {
    // 否则全选
    selectableIds.forEach(id => selectedEpisodeIds.value.add(id));
  }
};

/**
 * 清空所有选择
 */
const clearSelection = () => {
  selectedEpisodeIds.value.clear();
};

/**
 * 检查某个剧集是否被选中
 */
const isEpisodeSelected = (episodeId: number): boolean => {
  return selectedEpisodeIds.value.has(episodeId);
};

// --- Subtitle Delete Methods ---

/**
 * 批量删除选中的剧集字幕
 */
const deleteBatchSelectedSubtitles = async () => {
  if (selectedEpisodeIds.value.size === 0) {
    ElMessage.warning('请先选择要删除的剧集');
    return;
  }

  const selectedIds = Array.from(selectedEpisodeIds.value).sort((a, b) => a - b);
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.length} 个剧集的字幕吗？\n\n剧集ID: ${selectedIds.slice(0, 10).join(', ')}${selectedIds.length > 10 ? '...' : ''}\n\n操作不可撤销！`,
      '批量删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    deletingBatch.value = true;

    console.log(`🗑️ 开始批量删除选中剧集字幕: ${selectedIds.length}个剧集`);
    
    // 后台执行删除操作
    deleteBatchEpisodeSubtitles(selectedIds).then((result) => {
      if (result.success) {
        ElMessage.success(`批量删除成功！共删除了 ${result.deletedCount} 集的字幕`);
        
        // 刷新字幕数据
        loadSubtitleData(true);
        
        // 刷新字幕状态
        if (selectedDrama.value) {
          refreshSingleStatus(selectedDrama.value.id);
        }
      }
    }).catch((error) => {
      console.error('批量删除字幕失败:', error);
      ElMessage.error(`批量删除失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }).finally(() => {
      deletingBatch.value = false;
    });

    // 清空选择并立即恢复UI
    clearSelection();
    deletingBatch.value = false;
    ElMessage.info(`批量删除任务已启动，将在后台处理 ${selectedIds.length} 集的字幕删除`);
  } catch (error) {
    if (error === 'cancel') {
      console.log('用户取消批量删除操作');
      return;
    }
    console.error('批量删除字幕失败:', error);
    ElMessage.error(`批量删除失败: ${error instanceof Error ? error.message : '未知错误'}`);
  } finally {
    // 清理状态在后台删除的 finally 块中处理
  }
};

/**
 * 确认删除全部字幕
 */
const confirmDeleteAllSubtitles = () => {
  if (!selectedDrama.value) return;

  const totalEpisodes = filteredSubtitleEpisodes.value.length;
  const totalSubtitles = subtitles.value.filter(sub => sub.shortDramaId === selectedDrama.value!.id).length;

  ElMessageBox.confirm(
    `确定要删除短剧《${selectedDrama.value.title}》的全部字幕吗？\n\n这将删除 ${totalEpisodes} 集的 ${totalSubtitles} 个字幕文件，操作不可撤销！`,
    '危险操作确认',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'dangerous-confirm',
      distinguishCancelAndClose: true,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = '删除中...';
          deleteAllSubtitles().finally(() => {
            done();
          });
        } else {
          done();
        }
      }
    }
  ).catch(() => {
    // 用户取消删除
    console.log('用户取消删除操作');
  });
};

/**
 * 删除全部字幕
 */
const deleteAllSubtitles = async () => {
  if (!selectedDrama.value || deletingDrama.value) return;

  deletingDrama.value = true;

  try {
    console.log(`🗑️ 开始删除短剧《${selectedDrama.value.title}》的全部字幕`);
    
    // 后台执行删除操作
    deleteDramaSubtitles(
      selectedDrama.value.id,
      subtitles.value
    ).then((result) => {
      if (result.success) {
        ElMessage.success(`删除成功！共删除了 ${result.deletedCount} 集的字幕`);
        
        // 刷新字幕数据
        loadSubtitleData(true);
        
        // 刷新字幕状态
        if (selectedDrama.value) {
          refreshSingleStatus(selectedDrama.value.id);
        }
      }
    }).catch((error) => {
      console.error('删除字幕失败:', error);
      ElMessage.error(`删除失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }).finally(() => {
      deletingDrama.value = false;
    });

    // 立即恢复UI
    deletingDrama.value = false;
    ElMessage.info(`删除任务已启动，正在后台处理字幕删除`);
  } catch (error) {
    console.error('删除字幕失败:', error);
    ElMessage.error(`删除失败: ${error instanceof Error ? error.message : '未知错误'}`);
  } finally {
    // 清理状态在后台删除的 finally 块中处理
  }
};

/**
 * 删除单集字幕
 */
const deleteEpisodeSubtitle = async (episodeId: number) => {
  if (!selectedDrama.value || deletingEpisode.value) return;

  const episodeSubtitles = subtitles.value.filter(sub => sub.episodeId === episodeId);
  if (episodeSubtitles.length === 0) {
    ElMessage.warning(`剧集${episodeId}没有字幕需要删除`);
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除剧集${episodeId}的所有字幕吗？\n\n将删除该剧集的 ${episodeSubtitles.length} 个字幕文件，操作不可撤销！`,
      '确认删除',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    deletingEpisode.value = episodeId;

    console.log(`🗑️ 开始删除剧集${episodeId}的字幕`);

    const result = await deleteEpisodeSubtitles(episodeId);

    if (result.success) {
      ElMessage.success(`删除成功！删除了剧集${episodeId}的字幕`);
      
      // 刷新字幕数据
      await loadSubtitleData(true);
      
      // 刷新字幕状态
      if (selectedDrama.value) {
        await refreshSingleStatus(selectedDrama.value.id);
      }
    }
  } catch (error) {
    if (error === 'cancel') {
      console.log('用户取消删除操作');
      return;
    }
    console.error('删除剧集字幕失败:', error);
    ElMessage.error(`删除失败: ${error instanceof Error ? error.message : '未知错误'}`);
  } finally {
    deletingEpisode.value = null;
  }
};

onMounted(fetchDramas);

// 组件卸载时清理搜索
onUnmounted(() => {
  // 取消所有pending的搜索请求
  if (searchKeyword.value) {
    cancelDebouncedSearch(searchKeyword.value);
  }
  
  // 清理搜索状态
  clearSearch();
});
</script>

<style scoped>
/* 搜索信息样式 */
.search-info {
  padding: 8px 16px;
  background: #f0f9ff;
  border-top: 1px solid #e0f2fe;
  font-size: 14px;
  color: #0369a1;
}

.search-text {
  display: flex;
  align-items: center;
  gap: 4px;
}

.search-time {
  color: #64748b;
  font-size: 12px;
}

.pagination-info,
.search-info {
  border-bottom-left-radius: 6px;
  border-bottom-right-radius: 6px;
}

/* 搜索容器增强样式 */
.search-container {
  position: relative;
}

.search-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #e0e7ff;
  border-top: none;
  border-radius: 0 0 6px 6px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  z-index: 10;
  max-height: 200px;
  overflow-y: auto;
}

.suggestions-header {
  padding: 8px 12px;
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
  font-size: 12px;
  color: #64748b;
  font-weight: 500;
}

.suggestions-list {
  padding: 8px 12px;
}

/* Loading animation for search */
.search-info .is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 字幕状态样式 */
.item-subtitle-status {
  margin-left: 8px;
}

.status-tag {
  display: inline-flex;
  align-items: center;
  gap: 2px;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
}

.status-tag .el-icon {
  font-size: 12px;
}

.status-detail {
  font-size: 11px;
  color: #666;
  margin-left: 4px;
}

/* 状态加载动画 */
.status-tag .is-loading {
  animation: rotating 1.5s linear infinite;
}

/* 批量选择功能样式 */
.selection-section {
  border-left: 1px solid #e0e7ff;
  padding-left: 12px;
  margin-left: 12px;
}

/* 选中剧集ID显示功能样式 */
.selected-episodes-section {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
  border-left: 1px solid #e0e7ff;
  padding-left: 12px;
  margin-left: 12px;
  min-width: 300px;
  max-width: 500px;
}

.selected-episodes-display {
  width: 100%;
}

.episodes-tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 6px;
  max-height: 60px;
  overflow-y: auto;
}

.episode-id-tag {
  font-family: 'Monaco', 'Consolas', monospace;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.episode-id-tag:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.more-episodes-tag {
  font-size: 11px;
  opacity: 0.8;
}

.episodes-summary {
  border-top: 1px solid #f0f0f0;
  padding-top: 4px;
}

.summary-text {
  font-size: 12px;
  color: #666;
  font-family: 'Monaco', 'Consolas', monospace;
}

/* 删除功能样式 */
.delete-section {
  border-left: 1px solid #e0e7ff;
  padding-left: 12px;
  margin-left: 12px;
}

.delete-button {
  min-width: 120px;
}

.delete-button:disabled {
  opacity: 0.6;
}

/* 批量选择表格样式 */
.subtitle-table-container :deep(.el-table__header-wrapper) {
  .el-table__header {
    .el-checkbox {
      .el-checkbox__input.is-indeterminate .el-checkbox__inner {
        background-color: #409eff;
        border-color: #409eff;
      }
    }
  }
}

.subtitle-table-container :deep(.el-table__body-wrapper) {
  .el-table__row {
    .el-checkbox.is-disabled {
      opacity: 0.3;
    }
    
    .el-checkbox:not(.is-disabled):hover {
      .el-checkbox__inner {
        border-color: #409eff;
      }
    }
  }
}

/* 危险操作确认对话框样式 */
:deep(.dangerous-confirm) {
  .el-message-box__status {
    color: #f56c6c;
  }
  
  .el-message-box__title {
    color: #f56c6c;
  }
  
  .el-button--primary.is-loading {
    background-color: #f56c6c;
    border-color: #f56c6c;
  }
}

/* 字幕表格操作列样式 */
.subtitle-table-container :deep(.el-table__body-wrapper) {
  .el-table__row {
    .el-button--danger.is-small {
      padding: 4px 6px;
      font-size: 12px;
    }
    
    .el-button:disabled {
      opacity: 0.4;
    }
  }
}
</style>

<style scoped src="../styles/DramaList.css"></style>
